﻿using ShiSan.Blog.Server.Language;
using Microsoft.AspNetCore.Diagnostics;

namespace ShiSan.Blog.Web.Controllers;

/// <summary>
/// 
/// </summary>
[AllowAnonymous]
public class ErrorController : Controller
{
    // 处理特定状态码的错误，例如 /Error/404
    [Route("Error/{statusCode}")]
    public IActionResult HttpStatusCodeHandler(int statusCode)
    {
        var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();

        switch (statusCode)
        {
            case 404:
                ViewBag.ErrorMessage = i18n.page_not_exist;
                ViewBag.OriginalPath = statusCodeResult?.OriginalPath; // 捕获的原始路径
                ViewBag.QueryString = statusCodeResult?.OriginalQueryString; // 捕获的原始查询字符串
                break;
            // 可以根据需要添加其他状态码的处理，如400, 401, 500等
            case 500:
                ViewBag.ErrorMessage = i18n.server_error;
                break;
            default:
                ViewBag.ErrorMessage = i18n.unknown_error;
                break;
        }

        return View("NotFound"); // 返回一个统一的错误视图，或者根据状态码返回不同视图
    }

    // 处理全局未捕获的异常，通常指向 /Error
    [Route("Error")]
    [AllowAnonymous]
    public IActionResult Index()
    {
        // 获取异常详情
        var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        // 记录异常 exceptionHandlerPathFeature.Error 和路径 exceptionHandlerPathFeature.Path
        // ... 你的日志记录代码 ...

        ViewBag.ErrorMessage = i18n.request_error;
        ViewBag.ExceptionPath = exceptionHandlerPathFeature?.Path;
        ViewBag.ExceptionMessage = exceptionHandlerPathFeature?.Error.Message;
        ViewBag.StackTrace = exceptionHandlerPathFeature?.Error.StackTrace;

        return View("Error");
    }
}
